package com.yanqu.road.web.mgr;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.MallInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.servercenter.ChannelInfo;
import com.yanqu.road.entity.web.activity.GetActivityIdByServerIdReqParam;
import com.yanqu.road.entity.web.activity.GetActivityIdByServerIdRespParam;
import com.yanqu.road.logic.bussiness.servercenter.ActivityBussiness;
import com.yanqu.road.logic.bussiness.servercenter.ChannelActivityBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.http.HttpHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityMallMgr extends TempMgr {

	private static Map<Integer, Map<Integer, MallInfo>> activityMallInfoMap;

	@Override
	public boolean stop() {
		return false;
	}

	public boolean init() throws Exception {
		return reload();
	}

	@Override
	public boolean reloadConfig() throws Exception {
		return true;
	}

	@Override
	public boolean reloadData() {
		reloadActivityData();
		return true;
	}

	public static void reloadActivityData(){
		String nowTimeStr = DateHelper.getCurrentDateTimeString();
		List<Integer> activityTypeList = new ArrayList<>();
		activityTypeList.add(eActivityType.RMBMallActivity.getValue());
		activityTypeList.add(eActivityType.SystemOpenRMBMallActivity.getValue());
		activityTypeList.add(eActivityType.CrossRankActivity.getValue());
		activityTypeList.add(eActivityType.CrossUnionActivity.getValue());
		activityTypeList.add(eActivityType.CrossHuaShiGangActivity.getValue());
		activityTypeList.add(eActivityType.DaFuWeng.getValue());
		activityTypeList.add(eActivityType.CrossUnionWarActivity.getValue());
		activityTypeList.add(eActivityType.CrossDunHuangShiKuActivity.getValue());
		activityTypeList.add(eActivityType.CookingBoyActivity.getValue());
		activityTypeList.add(eActivityType.ChefDuel.getValue());
		activityTypeList.add(eActivityType.DouLuoDaLuActivity.getValue());
		activityTypeList.add(eActivityType.RechargeActivity.getValue());
		activityTypeList.add(eActivityType.ChineseChess.getValue());
		activityTypeList.add(eActivityType.TongBingActivity.getValue());
		activityTypeList.add(eActivityType.TonBingActivity.getValue());
		activityTypeList.add(eActivityType.ChuHanZB.getValue());
		activityTypeList.add(eActivityType.Pasture.getValue());
		activityTypeList.add(eActivityType.RankUnionWar.getValue());
		activityTypeList.add(eActivityType.GreatTradeActivity.getValue());
		activityTypeList.add(eActivityType.Cat.getValue());
		activityTypeList.add(eActivityType.Twins.getValue());
		activityTypeList.add(eActivityType.CricketSeasonActivity.getValue());
        activityTypeList.add(eActivityType.PeakStrongHold.getValue());
        activityTypeList.add(eActivityType.FlowerCards.getValue());
		activityTypeList.add(eActivityType.PeerlessBeautyLotteryActivity.getValue());
		activityTypeList.add(eActivityType.OperaMask.getValue());
        activityTypeList.add(eActivityType.OldPlayerReturn.getValue());
        activityTypeList.add(eActivityType.UnionChest.getValue());
        activityTypeList.add(eActivityType.CommonWishDraw.getValue());
        activityTypeList.add(eActivityType.CricketMallActivity.getValue());
        activityTypeList.add(eActivityType.FiveHero.getValue());
		activityTypeList.add(eActivityType.FestivalGift.getValue());
		activityTypeList.add(eActivityType.QiXiActivity.getValue());
		activityTypeList.add(eActivityType.GuaGiftsActivity.getValue());
		activityTypeList.add(eActivityType.EveFeast.getValue());
		activityTypeList.add(eActivityType.DaoMu.getValue());
		activityTypeList.add(eActivityType.JinLi.getValue());
		activityTypeList.add(eActivityType.SteleSoul.getValue());
		activityTypeList.add(eActivityType.NewFirstRechargeCash.getValue());
		activityTypeList.add(eActivityType.NewFirstRecharge2024.getValue());
		activityTypeList.add(eActivityType.JiuZhou.getValue());
		activityTypeList.add(eActivityType.SnowGarden.getValue());
		activityTypeList.add(eActivityType.SummerGames.getValue());
		activityTypeList.add(eActivityType.ActivityFund.getValue());
		activityTypeList.add(eActivityType.DoubleSpring.getValue());
		activityTypeList.add(eActivityType.ZhenHuan.getValue());
		activityTypeList.add(eActivityType.BiaoJu.getValue());
		activityTypeList.add(eActivityType.SuiTang.getValue());
		activityTypeList.add(eActivityType.SonHai.getValue());
		activityTypeList.add(eActivityType.HsIsland.getValue());
		activityTypeList.add(eActivityType.CombLeaderFund.getValue());
		activityTypeList.add(eActivityType.HorseRun.getValue());
		activityTypeList.add(eActivityType.GoldIngotFund.getValue());
		activityTypeList.add(eActivityType.HotpotJump.getValue());
		activityTypeList.add(eActivityType.StarLight.getValue());
		activityTypeList.add(eActivityType.IceServerGift.getValue());
		activityTypeList.add(eActivityType.Apprentice.getValue());
  		activityTypeList.add(eActivityType.WealthScroll.getValue());
		activityTypeList.add(eActivityType.NewPatronsFund.getValue());

        boolean getActivityByUrl = false;
		Map<Integer, ActivityInfo> activityInfoMap = null;
		int channelId = ServerListMgr.getChannelId(WebServer.getInstance().getServerId());
		ChannelInfo channelInfo = ServerListMgr.getChannelInfo(channelId);
		if(channelInfo != null && !StringUtils.isNullOrEmpty(channelInfo.getGetActivityUrl())){
			GetActivityIdByServerIdReqParam getActivityIdByServerIdReqParam  = new GetActivityIdByServerIdReqParam();
			getActivityIdByServerIdReqParam.setType(2);
			getActivityIdByServerIdReqParam.setServerId(Integer.parseInt(ConfigHelper.getValue("serverId")));
			getActivityIdByServerIdReqParam.setServerTime(System.currentTimeMillis()/1000);
			getActivityIdByServerIdReqParam.setTypeList(activityTypeList);

			Map<String, String> resultMap = HttpHelper.httpPostJson(channelInfo.getGetActivityUrl(), JSONObject.toJSONString(getActivityIdByServerIdReqParam), "UTF-8", new HashMap<>(),
					ChannelConfig.CN_FORBIDDEN_WORD_CHECK_SOCKET_TIME_OUT,
					ChannelConfig.CN_FORBIDDEN_WORD_CHECK_CONNECT_TIME_OUT,
					ChannelConfig.CN_FORBIDDEN_WORD_CHECK_CONNECT_REQUEST_TIME_OUT);    //1秒超时时间
			if (resultMap != null && "200".equals(resultMap.get("code"))) {
				String resultStr = resultMap.get("body");
				GetActivityIdByServerIdRespParam getActivityIdByServerIdRespParam = JSONObject.parseObject(resultStr, GetActivityIdByServerIdRespParam.class);
				if (getActivityIdByServerIdRespParam.getActivityIdList().size() == 0) {
					getLogger().debug("not found activity");
				} else {
					getLogger().debug("find activity {}", JSONObject.toJSONString(getActivityIdByServerIdRespParam));
					activityInfoMap = ActivityBussiness.getActivityInfoMap(getActivityIdByServerIdRespParam.getActivityIdList());
					getActivityByUrl = true;
				}
			}
		}

		if (!getActivityByUrl) {
			activityInfoMap = ActivityBussiness.getRMBMallActivityInfoMap(activityTypeList, WebServer.getInstance().getServerId(), nowTimeStr);
		}


		Map<Integer, Map<Integer, MallInfo>> tmpMap = new ConcurrentHashMap<>();
		// 添加活动商店
		if (activityInfoMap.size() > 0) {
			List<Integer> dataList = new ArrayList<>(activityInfoMap.keySet());
			tmpMap = ActivityBussiness.getActivityMallInfoMap(dataList);
		}
		// 添加跨地区商店
		mergeCrossChannelMall(tmpMap);
		// 替换
		activityMallInfoMap = tmpMap;
	}

	/**
	 * 添加跨地区商店
	 */
	private static void mergeCrossChannelMall(Map<Integer, Map<Integer, MallInfo>> activityMallInfoMap) {
		// 先检查有没有数据库连接配置
		String dbParam = ChannelConfig.CHANNEL_CENTER_DB_PARAM;
		if ("0".equals(dbParam)) {
			getLogger().info("[ ChannelConfig.CHANNEL_CENTER_DB_PARAM ] is zero!");
			return;
		}
		long serverId = WebServer.getInstance().getServerId();
		int channelId = ServerListMgr.getChannelId(serverId);
		// 全部活动
		Map<Integer, ActivityInfo> infoMap = ChannelActivityBussiness.getAllActivityInfoMap(dbParam, serverId, ChannelConfig.CHANNEL_ACTIVITY_TIME_ZONE);
		// 瓦舍活动
		Map<Integer, ActivityInfo> recentWasheInfoMap = ChannelActivityBussiness.getRecentWasheActivityInfoMap(dbParam, channelId, ChannelConfig.CHANNEL_ACTIVITY_TIME_ZONE);
		for (ActivityInfo washeInfo : recentWasheInfoMap.values()) {
			infoMap.put(washeInfo.getActivityId(), washeInfo);
		}
		List<Integer> idList = new ArrayList<>();
		// 提前24小时加载
		long nowTime = System.currentTimeMillis() / 1000;
		for (ActivityInfo info : infoMap.values()) {
			if (nowTime >= (info.getBeginShowTime() - DateHelper.DAY_SECONDS) && nowTime < info.getEndShowTime()) {
				idList.add(info.getActivityId());
			}
		}
		if (idList.size() > 0) {
			Map<Integer, Map<Integer, MallInfo>> mallInfo = ChannelActivityBussiness.getActivityMallInfoMap(dbParam, idList);
			for (Map<Integer, MallInfo> value : mallInfo.values()) {
				for (MallInfo info : value.values()) {
					if (info.getChannelId() != 0 && info.getChannelId() != channelId) {
						continue;
					}
					// 添加到map
					if (!activityMallInfoMap.containsKey(info.getActivityId())) {
						activityMallInfoMap.put(info.getActivityId(), new ConcurrentHashMap<>());
					}
					Map<Integer, MallInfo> map = activityMallInfoMap.get(info.getActivityId());
					map.put(info.getMallId(), info);
				}
			}
		}
	}

	public static MallInfo getMallInfo(int mallId) {
		for(Map<Integer, MallInfo> mallInfoMap : activityMallInfoMap.values()){
			MallInfo mallInfo = mallInfoMap.get(mallId);
			if(null != mallInfo){
				return mallInfo;
			}
		}
		return null;
	}
}
